import { getToken, setToken } from "@/utils/auth";
import Vue from "vue";
import Vuex from "vuex";
import { getUserInfo, login } from "@/api/login";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userInfo: null,
    token: getToken(),
    redirectPath: "",
    projectId: "",
  },
  getters: {},
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
      setToken(token);
    },
    SET_USERINFO: (state, v) => {
      state.userInfo = v;
    },
    SET_REDIRECT_PATH: (state, { fullPath, params }) => {
      state.redirectPath = fullPath;
      if (params && params.id) {
        state.projectId = params.id;
      }
    },
  },
  actions: {
    GetUserInfo({ commit }) {
      return getUserInfo().then(({ entity }) => {
        commit("SET_USERINFO", entity);
      });
    },
    LogIn({ commit }, params) {
      return login(params).then(({ data }) => {
        commit("SET_TOKEN", data.access_token);
      });
    },
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        // 暂时没有退出接口
        commit("SET_TOKEN", "");
        commit("SET_USERINFO", null);
        resolve();
      });
    },
  },
  modules: {},
});
